import qrcode
from django import forms

from django.http import HttpResponse
from django.shortcuts import render
from rest_framework import generics, mixins
# Create your views here.
from .models import Person
from .serializers import PersonSerializer
from rest_framework import status
from rest_framework.response import Response
from .filters import PersonFilter
from django.conf import settings
import uuid
import os
from .form import PersonFrom


class UsersListView(mixins.CreateModelMixin, mixins.ListModelMixin, generics.GenericAPIView):
    """
    对用户增加
    """
    queryset = Person.objects.all()
    serializer_class = PersonSerializer
    filter_class = PersonFilter

    def get(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)

        res_data = {}
        res_data['code'] = '200'

        if page is not None:
            serializer = self.get_serializer(page, many=True)
            res_data = self.get_paginated_response(serializer.data)
            res_data.data['code'] = "200"
            return res_data

        serializer = self.get_serializer(queryset, many=True)
        res_data['data'] = serializer.data
        res_data['count'] = len(queryset)

        return Response(res_data)

    def post(self, request, *args, **kwargs):

        return self.create(request, *args, **kwargs)

        # <QueryDict: {'card_id': ['3'], 'name': ['单应敏'], 'permanent_residence': ['河北'], 'mobile': ['13217745443'], 'gender': ['1'], 'age': ['21'], 'is_vaccine': ['true']}>

        # return self.list(request,*args, **kwargs)
        users = request.data.get('users')
        data = []

        for user in users:
            # {"card_id": "0", "name": "何瞰", "permanent_residence": "河南省", "mobile": "18839460901",   "gender": "2", "age": 98, "is_vaccine": false, | "status": "1", "image": "http://121.196.107.223:8000/img/127.jpeg"}
            serializer = self.get_serializer(data=user)
            try:
                serializer.is_valid(raise_exception=True)
                serializer.save()
                print("创建了", serializer.data)
            except:
                print('创建失败了')
                continue
            data.append(serializer.data)
        return Response(data, status=status.HTTP_201_CREATED)
        # post方法接受用户发过来的请求数据后，有时只需转发不需要创建模式对象实例，所以post方法不能简单等于create方法


class UsersQRListView(generics.GenericAPIView):

    def get(self, request):
        try:
            # url = request.
            card_id = uuid.uuid4().hex[:10]
            filename = '{}.{}'.format(card_id, 'png')
            qr = qrcode.QRCode(
                version=2,
                error_correction=qrcode.constants.ERROR_CORRECT_L,
                box_size=10,
                border=1
            )
            qr.add_data("http://coderxiaomo.top:10080/users/users_qr/{}".format(card_id))
            qr.make(fit=True)
            img = qr.make_image()
            img.save(filename)
            if os.path.exists(filename):
                qrimg_data = open(filename, 'rb').read()
                return HttpResponse(qrimg_data, content_type="image/png")
        except Exception as e:
            return HttpResponse(str(e))


class UsersQRDetailView(generics.GenericAPIView):
    serializer_class = PersonSerializer

    def get(self, request, card_id):
        """
        扫码绑定卡号的，获取提交表单页面
        :param request:
        :return:
        """

        form = PersonFrom(initial={
            'card_id': card_id
        })
        # form.fields['card_id'].widget = forms.HiddenInput()
        return render(request, 'users/qr_form.html', {'form': form})


class UsersAdminListView(mixins.CreateModelMixin, mixins.ListModelMixin, generics.GenericAPIView):
    """
    对用户增加
    """
    queryset = Person.objects.all()
    serializer_class = PersonSerializer

    # filter_class = PersonFilter

    def get(self, request, *args, **kwargs):
        """

        :param request:
        :param args:
        :param kwargs:
        :return: [
                {
                    "type": "家具家电",
                    "sales": 38
                }
            ]
        """
        queryset = self.get_queryset()
        queryset.filter(is_vaccine=False)

        res_data = []
        res_data.append({'type': '未接种疫苗', 'value': len(queryset.filter(is_vaccine=False))})
        res_data.append({'type': '已接种疫苗', 'value': len(queryset.filter(is_vaccine=True))})
        res_data.append({'type': '健康', 'value': len(queryset.filter(status='1'))})
        res_data.append({'type': '密切接触', 'value': len(queryset.filter(status='2'))})
        res_data.append({'type': '感染', 'value': len(queryset.filter(status='3'))})
        # res_data['data'] = None
        # res_data['code'] = '200'
        # res_data['count'] = len(queryset)
        return Response(res_data)


class UsersDetailView(mixins.UpdateModelMixin, mixins.RetrieveModelMixin,
                      mixins.DestroyModelMixin, generics.GenericAPIView):
    """
    对单个用户
    1.增加
    2.更新
    3.查询
    4.删除
    """
    queryset = Person.objects.all()
    serializer_class = PersonSerializer

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)
